const Downloader = require('nodejs-file-downloader');
const async = require('async');
const fileUtils = require('./fileUtils');
const path = require('path');
const TaskStatus = require('./taskStatus');
const Task = require('./task');
const log = require('electron-log');
const Store = require('electron-store');
const getUserDataPath = require('./getUserDataPath');
const minioFileUpload = require('./minio');
const FileInfo = require('./fileInfo');
const Http = require('./http.js');
const http = new Http();
const configManager = require('./config');
const fs = require('fs');

const store = new Store({
    name: 'sync',
    cwd: getUserDataPath(),
});

const user = store.get('user');

log.info('引入service2');

/*
 * @Description: 文件传输服务
 */
class FileTransferService {
    constructor() {
        this.downloadTaskList = [];
        this.uploadTaskList = [];
        this.task = null;
    }

    async GetDownDetail(task, detail) {
        return new Promise(async(resolve, reject) => {
            const compresssPromise = [];
            let data = {
                mid: user.mid,
                taskId: task.GetID(),
                busId: task.GetBusId(),
                pjId: task.GetPjId(),
                taskDetailExecute: detail ? detail : null,
            };
            // log.info({ params: data });
            const res = await http.request(
                'POST',
                '/bimfile/doc-sync/processTaskDetail',
                data
            );

            log.info({ data: res.data });
            // const lastDetail = res.data.lastDetail;
            if (res.data.node) {
                const file = res.data.node;
                const folder = configManager.getLocal().folderPath;
                const local = path.join(folder, task.GetPjName());
                const localPath = file.dirPath ? path.join(local, file.dirPath) : local;

                const downloader = new Downloader({
                    fileName: file.docName,
                    url: file.downloadUrl,
                    directory: localPath,
                    cloneFiles: false,
                    onProgress: async(percentage, chunk, remainingSize) => {},
                });

                
                try{
                     const resdata = await downloader.download();
                     if (resdata.downloadStatus === 'COMPLETE') {
                        log.info('下载成功:' + localPath + '/' + file.docName);
                        const promiseProgress = await this.GetDownDetail(task, {
                            nodeId: file.nodeId,
                            nodeType: file.nodeType,
                            executeStatus: 3,
                            fileId: file.fileId,
                        });
                        compresssPromise.push(promiseProgress);
                    } else {
                        log.info('下载失败:' + file.docName);
                        const promiseProgress = await this.GetDownDetail(task, {
                            nodeId: file.nodeId,
                            nodeType: file.nodeType,
                            executeStatus: 4,
                            fileId: file.fileId,
                        });
                        compresssPromise.push(promiseProgress);
                    }

                }catch{
                    
                    const promiseProgress = await this.GetDownDetail(task, {
                        nodeId: file.nodeId,
                        nodeType: file.nodeType,
                        executeStatus: 4,
                        fileId: file.fileId,
                    });
                    compresssPromise.push(promiseProgress);
                }

                


               
            }

            resolve('下载完成');

            try {
                const result = Promise.all(compresssPromise);
                resolve(result);
            } catch {
                log.info(error);
                reject(error);
            }
        });
    }
    getFolderPath(filePath) {
        let projectname = path.relative(
            configManager.getLocal().folderPath,
            filePath
        );

        let names = path.dirname(projectname);

        let logs = names.replace(/\\/g, '/');

        let name = logs.split('/')[0];
        let folder = logs.split('/').slice(1, logs.split('/').length).join('/');

        return folder;
    }

    statAsync(path) {
        return new Promise((resolve, reject) => {
            fs.stat(path, (err, stats) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(stats);
            });
        });
    }

    async GetUploadDetail(task, detail) {
        return new Promise(async(resolve, reject) => {
            const compresssPromise = [];
            let data = {
                mid: user.mid,
                taskId: task.GetID(),
                // busId: task.GetBusId(),
                // pjId: task.GetPjId(),
                taskDetailExecute: detail ? detail : null,
            };
            log.info({ params: data });
            const res = await http.request(
                'POST',
                '/bimfile/doc-sync/processTaskDetail',
                data
            );

            log.info({ data: res.data });
            // const lastDetail = res.data.lastDetail;
            if (res.data.node) {
                const file = res.data.node;

                if (!fs.existsSync(file.dirPath)) {
                    const promiseProgress = await this.GetUploadDetail(task, {
                        taskDetailId: res.data.nextDetailId,
                        executeStatus: 4,
                    });
                    compresssPromise.push(promiseProgress);
                } else {
                    const stat = await this.statAsync(file.dirPath);
                    const minio = new minioFileUpload({
                        fileSize: stat.size,
                        fileName: file.nodeName,
                        filePath: file.dirPath,
                        dirPath: this.getFolderPath(file.dirPath),
                        busId: file.busId,
                        updateId: file.nodeId,
                    });
                    const resdata = await minio.uploads();
                    const promiseProgress = await this.GetUploadDetail(task, {
                        taskDetailId: res.data.nextDetailId,
                        executeStatus: resdata.executeStatus,
                        nodeId: resdata.nodeId,
                        fileId: resdata.fileId,
                    });
                    compresssPromise.push(promiseProgress);
                }
            }

            resolve('上传完成');

            try {
                const result = Promise.all(compresssPromise);
                resolve(result);
            } catch {
                log.info(error);
                reject(error);
            }
        });
    }

    InitializeDownload(downloadPort) {
        this.downloadTasks = async.queue((task, callback) => {
            task.SetStatus(TaskStatus.RUNNING);
            try {
                this.GetDownDetail(task, null)
                    .then(() => {
                        task.SetStatus(TaskStatus.SUCCESS);
                        log.info('task：' + task.GetID() + '下载成功');
                        downloadPort.postMessage({
                            type: 'file:download:success',
                            task,
                        });
                        callback();
                    })
                    .catch((error) => {
                        log.info({ error });
                    });
            } catch (error) {
                log.info({ error });
            }
        }, 1);
    }

    InitializeUpload(uploadPort) {
        this.uploadTasks = async.queue((task, callback) => {
            task.SetStatus(TaskStatus.RUNNING);
            try {
                this.GetUploadDetail(task, null)
                    .then(() => {
                        task.SetStatus(TaskStatus.SUCCESS);
                        log.info('task：' + task.GetID() + '上传成功');
                        uploadPort.postMessage({
                            type: 'file:upload:success',
                            task,
                        });
                        callback();
                    })
                    .catch((error) => {
                        log.info({ error });
                    });
            } catch (error) {
                log.info({ error });
            }
        }, 1);
    }

    CreateDownloadTask() {
        this.task = new Task();
        this.downloadTasks.push(this.task, (err) => {});
        this.downloadTaskList.push(this.task);
        return this.task;
    }

    CreateUploadTask() {
        this.task = new Task();
        this.uploadTasks.push(this.task, (err) => {});
        this.uploadTaskList.push(this.task);
        return this.task;
    }

    GetDownloadTaskList(status) {
        return this.downloadTaskList.filter(
            (x) => (status & x.status) === x.status
        );
    }

    GetUploadTaskList(status) {
        return this.uploadTaskList.filter((x) => (status & x.status) === x.status);
    }
}

module.exports = FileTransferService;